package cn.tedu.hongbeifang.security;

import cn.tedu.hongbeifang.mapper.AdminMapper;
import cn.tedu.hongbeifang.pojo.vo.AdminByNameVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * UserDetailsService:
 * @Auther:fzd
 * @Date:2023/3/6
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
     AdminMapper mapper;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.debug("登录业务启动!!!!");
        AdminByNameVO standardByName = mapper.getStandardByName(s);
        if(standardByName==null){
            return null;
        }
        List<GrantedAuthority> authorities = new ArrayList<>();
        List<String> permissions = standardByName.getPermissions();
        for(String permission : permissions){
            authorities.add(new SimpleGrantedAuthority(permission));
        }


        AdminDetails adminDetails = new AdminDetails(
                standardByName.getId(),
                standardByName.getUsername(),
                standardByName.getPassword(),
                standardByName.getEnable()==1,
                authorities);
        return adminDetails;
    }
}
